package com.mengxj;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author mengxj
 */
public class MapDemo {

    private static Map<String, String> map = new HashMap<>();

    static {
        map.put("student.age", "12");
        map.put("student.family.mother", "翠花");
        map.put("student.address", "长春");
        map.put("student.school.class.floor", "4");
        map.put("teacher.school.class", "一年一班");
        map.put("teacher.school.class1", "一年一班1");
        map.put("student.family.father", "张三");
        map.put("student.school.class.teacher", "李四");
    }

    /**
     * student.age 12
     * student.family.mother 翠花
     * student.address 长春
     * student.family.father 张三
     * student.school.class.teacher 李四
     * student.school.class.floor 4
     * teacher.school.class 一年一班
     * @param args
     */
    public static void main(String[] args) {
        Map<String, Object> res = new HashMap<>();
        map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> {
            String k = entry.getKey(), v = entry.getValue();
            String[] keys = k.split("[.]");
            String lastKey = null;
            Map<String, Object> innerRes = res;
            for(int i = 0; i < keys.length; i ++){
                String key = keys[i];
                if(i == 0){
                    lastKey = key;
                    innerRes = res;
                    continue;
                }
                Map<String, Object> value = (Map<String, Object>)innerRes.get(lastKey);
                if(Objects.isNull(value)){
                    value = new HashMap<>();
                    innerRes.put(lastKey, value);
                }
                if(i == keys.length - 1){
                    value.put(key, v);
                }
                lastKey = key;
                innerRes = value;
            }
        });
        System.out.println(JSON.toJSONString(res));
    }
}
